/**
    JavaScript module for KB Main page.
    TODO: Add handler for ajax errors
*/
Main = function() {
    function hide_all() {
        $('#query_results').hide();
        $('#reconstitute_results').hide();
		$('#error_messages').hide();
    }
    
    function load_lookup_table() {
        hide_all();
		Status.show('Loading lookup table...');
        var tablename = $("#tablename_select option:selected").text();
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/load_table',
            data:{'tablename':tablename},
            success:function(result) {
                display_lookup_table(result.data, '#reconstitute_results', 'reconstitute_table', '#error_messsages', true);
            }
        });
        return false;
    }
    
    function query_knowledgebase() {
        hide_all();
		Status.show('Performing query...');
        var object = $('#query').val();
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/query',
            data:{'object':object},
            success:function(result) {
                display_queryresults_table(result.data, '#query_results', 'query_results_table', '#error_messages');
            }
        });
        return false;
    }
    
    function load_factfrequency_table() {
        hide_all();
		Status.show('Loading fact frequency lookup table...');
        var tablename = $("#tablename_select option:selected").text();
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/factfrequency',
            data:{},
            success:function(result) {
                display_lookup_table(result.data, '#reconstitute_results', 'reconstitute_table', '#error_messsages', false);
            }
        });
        return false;
    }
    
    function display_queryresults_table(data_list, container, table, errorContainer) {
		if(!data_list || data_list.length == 0) {
			$(container).hide();
			$(errorContainer).show();
		}
		else {
			display_data = getResultArray(data_list);
			column_data = getColumnArray(data_list['columns']);
			$(container).show();
			$(errorContainer).hide();
			var tid = '#' + table;
			$(tid + ' tr,' + tid + ' th').remove();
			$(tid).dataTable({
				'bDestroy'		 : true, //Brutally murder any existing dataTable first
				'bFilter'		 : false, //Hide the search box
				'aaData'		 : display_data,
				'aoColumns'		 : column_data,
				'iDisplayLength' : 100
			});
		}
    }
	
	function getResultArray(data_list) {
		var data = [];
		$.each(data_list, function(key, value) {
			if(key != 'columns'){
				data.push(value);
			}
		});
		return data;
	}
	
	function getColumnArray(column_list) {
		var columns = []
		$.each(column_list, function(index, value) {
			columns.push({'sTitle': value});
		});
		return columns;
	}
    
    function reconstitute_object(object) {
		Status.show('Performing reconstitution...');
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/reconstitute',
            data:{'object':object},
            success:function(result) {
                display_data_table(result.data, '#reconstitute_results', 'reconstitute_table', '#error_messages');
            }
        });
        return false;
    }
    
    function display_data_table(data_list, container, table, errorContainer) {
		
		if(data_list.length == 0) {
			$(container).hide();
			$(errorContainer).show();
		}
		else {
			$(container).show();
			$(errorContainer).hide();
			var tbody = $('<tbody>').attr('id',table);
			$.each(data_list, function(index,item) {
			  var tr = $('<tr>')
			  $('<td>').text(item.id).appendTo(tr);
			  var tmp_val = null;
			  if ($.isArray(item.value)) {
				  tmp_val = item.value.join(', ');
			  } else {
				  tmp_val = item.value;
			  }
			  $('<td>').text(tmp_val).appendTo(tr);
			  tr.appendTo(tbody);
			});
			var tid = '#' + table;
			$(tid).replaceWith(tbody);
		}
    }
    
    function display_lookup_table(data_list, container, table, errorContainer, nested) {
		if(data_list.length == 0) {
			$(container).hide();
			$(errorContainer).show();
		}
		else {
			$(container).show();
			$(errorContainer).hide();
			var tbody = $('<tbody>').attr('id',table);
			$.each(data_list, function(index,item) {
			  var item_id = item.id;
			  if (nested) { item = item.value; }
			  var tr = $('<tr>')
			  $('<td>').text(item_id).appendTo(tr);
			  var tmp_val = null;
			  if ($.isArray(item.value)) {
				  tmp_val = item.value.join(', ');
			  } else {
				  tmp_val = item.value;
			  }
			  $('<td>').text(tmp_val).appendTo(tr);
			  $('<td>').text(item.frequency).appendTo(tr);
			  tr.appendTo(tbody);
			});
			var tid = '#' + table;
			$(tid).replaceWith(tbody);
		}
    }
        
    return {
        init : function(conf) {
            var config = conf || {};
            
			/** configure visibility */
			hide_all();
            
			/** hook up events */
            $('#tablename_select').change(function() { load_lookup_table(); });
			
			/** co-opt form submission for queries */
            $('#query_form').submit(function(event) {
				event.preventDefault();
				query_knowledgebase();
			});
			
			/** Handle resets to hide status and results */
			$('#reset').click(function() {
			    $('#reconstitute_results').hide();
				$('#error_messages').hide();
				$('#query_results').hide();
			    Status.hide();
			});
			
			$('#factfreq').click(function() { load_factfrequency_table(); })
			
			/** auto-focus the input */
			$('#query').focus();
			
			//Global ajax event handling. We have to bind this to SOMETHING, but
			// that has no real bearing on what we're doing here. All events
			// of the appropriate types will come here.
			$('#do_reconstitute').ajaxComplete(function(){
				Status.hide();
			});
			$('#do_reconstitute').ajaxError(function(event, request, settings, exception){
				alert(exception);
			});
        }
    }
}();
    
    
